import 'package:ctrip_flutter/app/dao/home_dao.dart';
import 'package:ctrip_flutter/app/model/common_model.dart';
import 'package:ctrip_flutter/app/model/grid_nav_model.dart';
import 'package:ctrip_flutter/app/model/home_model.dart';
import 'package:ctrip_flutter/app/model/sales_box_model.dart';
import 'package:ctrip_flutter/app/pages/search_page.dart';
import 'package:ctrip_flutter/app/utils/navigator_util.dart';
import 'package:ctrip_flutter/app/widget/grid_nav.dart';
import 'package:ctrip_flutter/app/widget/loading_container.dart';
import 'package:ctrip_flutter/app/widget/local_nav.dart';
import 'package:ctrip_flutter/app/widget/sales_box.dart';
import 'package:ctrip_flutter/app/widget/search_bar.dart';
import 'package:ctrip_flutter/app/widget/sub_nav.dart';
import 'package:ctrip_flutter/app/widget/webview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

const SEARCH_BAR_DEFAULT_TEXT = '网红打卡地 景点 酒店 美食';

class HomePage extends StatefulWidget {
  var mContext;

  HomePage(this.mContext);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var parentContext; //声明
  String resultString = '';
  List<CommonModel> bannerList = [];
  double appBarAlpha = 0.0;
  static const APPBAR_SCROLL_OFFSET = 111.0;

  List<CommonModel> localNavList = [];
  GridNavModel gridNavModel;
  List<CommonModel> subNavList = [];
  SalesBoxModel salesBoxModel;

  bool _loading = true;

  _onScroll(offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
    print("$offset / $alpha");
  }

  String showResult = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _refresh();
  }

  Future<Null> _refresh() async {
    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        localNavList = model.localNavList;
        bannerList = model.bannerList;
        gridNavModel = model.gridNav;
        subNavList = model.subNavList;
        salesBoxModel = model.salesBox;
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    parentContext = widget.mContext; //赋值
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.amberAccent),
      home: LoadingContainer(
          isLoading: _loading,
          child: Scaffold(
            backgroundColor: ColorUtil.color('f1f1fa'),
            body: Stack(
              children: <Widget>[
                MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: RefreshIndicator(
                      child: NotificationListener(
                          onNotification: (notification) {
                            if (notification is ScrollUpdateNotification &&
                                notification.depth == 0) {
                              _onScroll(notification.metrics.pixels);
                            }
                          },
                          child: ListView(
                            children: <Widget>[
                              Container(
                                height: 200,
                                child: Swiper(
                                  itemCount: bannerList.length,
                                  autoplay: true,
                                  itemBuilder: (context, index) {
                                    return GestureDetector(
                                      onTap: () {
                                        NavigatorUtil.push(
                                            parentContext,
                                            WebView(
                                              url: bannerList[index].url,
                                            ));
                                      },
                                      child: Image.network(
                                        bannerList[index].icon,
                                        fit: BoxFit.fill,
                                      ),
                                    );
                                  },
                                  pagination: new SwiperPagination(), //指示器
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.all(5),
                                child: LocalNav(
                                  parentContext: parentContext,
                                  localNavList: localNavList,
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 5, right: 5),
                                child: GridNav(
                                  parentContext: parentContext,
                                  gridNavModel: gridNavModel,
                                ),
                              ),
                              Padding(
                                padding:
                                    EdgeInsets.only(left: 5, top: 5, right: 5),
                                child: SubNav(
                                  parentContext: parentContext,
                                  subNavList: subNavList,
                                ),
                              ),
                              Padding(
                                padding:
                                    EdgeInsets.only(top: 5, left: 5, right: 5),
                                child: SalesBox(
                                  parentContext: parentContext,
                                  salesBox: salesBoxModel,
                                ),
                              )
                            ],
                          )),
                      onRefresh: _refresh),
                ),
                _appBar
              ],
            ),
          )),
    );
  }

  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              //AppBar渐变遮罩背景
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
            height: appBarAlpha > 0.2 ? 0.5 : 0,
            decoration: BoxDecoration(
                boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]))
      ],
    );
  }

  _jumpToSearch() {
    NavigatorUtil.push(
        context,
        SearchPage(
          hint: SEARCH_BAR_DEFAULT_TEXT,
        ));
  }

  _jumpToSpeak() {
//    NavigatorUtil.push(context, SpeakPage());
  }
}
